const screenElement = document.getElementById("ml_body_screen");
const gridCanvas = document.getElementById('gridCanvas');
const waveformCanvas = document.getElementById('waveformCanvas');
const gridCtx = gridCanvas.getContext('2d');
const waveformCtx = waveformCanvas.getContext('2d');

// 设置 gridCanvas 大小
// gridCanvas.width = window.innerWidth;
// gridCanvas.height = window.innerHeight;
// 使用 clientWidth 和 clientHeight，确保不包含 padding 和边框
gridCanvas.width = screenElement.clientWidth;
gridCanvas.height = screenElement.clientHeight;
waveformCanvas.width = screenElement.clientWidth;
waveformCanvas.height = screenElement.clientHeight;
console.log(`================> ${gridCanvas.width}, ${gridCanvas.height}, ${screenElement.clientWidth}`);
// 边距
const margin = 50;
///线条颜色
const lineColor = '#ffffff';
// 刻度参数
const xMin = 0; // X 轴最小刻度
const xMax = 50; // X 轴最大刻度
const yMin = -20; // Y 轴最小刻度
const yMax = 20; // Y 轴最大刻度

// 绘制网格
function drawGrid() {
    const width = gridCanvas.width - 2 * margin;
    const height = gridCanvas.height - 2 * margin;

    // 计算 X 轴和 Y 轴的刻度范围
    const xRange = xMax - xMin;
    const yRange = yMax - yMin;

    // 计算每个刻度的像素大小
    const xScale = width / xRange; // X 轴每个单位对应的像素
    const yScale = height / yRange; // Y 轴每个单位对应的像素

    gridCtx.strokeStyle = lineColor;
    gridCtx.lineWidth = 0.5;

    // 绘制垂直网格线（X 轴）
    for (let x = xMin; x <= xMax; x++) {
        ///判断是不是被5整除
        if (x % 5 !== 0) {
            continue;
        }
        const pixelX = margin + (x - xMin) * xScale;
        gridCtx.beginPath();
        gridCtx.moveTo(pixelX, margin);
        gridCtx.lineTo(pixelX, gridCanvas.height - margin);
        gridCtx.setLineDash([3, 3]);

        gridCtx.stroke();
    }

    // 绘制水平网格线（Y 轴）
    for (let y = yMin; y <= yMax; y++) {
        ///判断是不是被5整除
        if (y % 5 !== 0) {
            continue;
        }
        const pixelY = gridCanvas.height - margin - (y - yMin) * yScale;
        gridCtx.beginPath();
        gridCtx.moveTo(margin, pixelY);
        gridCtx.lineTo(gridCanvas.width - margin, pixelY);
        gridCtx.setLineDash([3, 3]);

        gridCtx.stroke();
    }

    // 绘制大格子的虚线
    gridCtx.strokeStyle = lineColor;
    gridCtx.lineWidth = 1;
    gridCtx.setLineDash([5, 5]);

    // 绘制垂直大网格线（每 10 个单位一个大刻度）
    if (false) {
        for (let x = xMin; x <= xMax; x += 10) {
            const pixelX = margin + (x - xMin) * xScale;
            gridCtx.beginPath();
            gridCtx.moveTo(pixelX, margin);
            gridCtx.lineTo(pixelX, gridCanvas.height - margin);
            gridCtx.stroke();
        }

        // 绘制水平大网格线（每 10 个单位一个大刻度）
        for (let y = yMin; y <= yMax; y += 10) {
            const pixelY = gridCanvas.height - margin - (y - yMin) * yScale;
            gridCtx.beginPath();
            gridCtx.moveTo(margin, pixelY);
            gridCtx.lineTo(gridCanvas.width - margin, pixelY);
            gridCtx.stroke();
        }
    }

    gridCtx.setLineDash([]); // 重置虚线样式
}

// 绘制坐标轴
function drawAxes() {
    const width = gridCanvas.width - 2 * margin;
    const height = gridCanvas.height - 2 * margin;

    // 计算 X 轴和 Y 轴的刻度范围
    const xRange = xMax - xMin;
    const yRange = yMax - yMin;

    // 计算每个刻度的像素大小
    const xScale = width / xRange; // X 轴每个单位对应的像素
    const yScale = height / yRange; // Y 轴每个单位对应的像素

    gridCtx.strokeStyle = lineColor;
    gridCtx.lineWidth = 0.5;

    // 绘制 X 轴（下边）
    gridCtx.beginPath();
    gridCtx.moveTo(margin, gridCanvas.height - margin);
    gridCtx.lineTo(gridCanvas.width - margin, gridCanvas.height - margin);
    gridCtx.stroke();

    // 绘制 X 轴（上边）
    gridCtx.beginPath();
    gridCtx.moveTo(margin, margin);
    gridCtx.lineTo(gridCanvas.width - margin, margin);
    gridCtx.stroke();

    // 绘制 Y 轴（左边）
    gridCtx.beginPath();
    gridCtx.moveTo(margin, margin);
    gridCtx.lineTo(margin, gridCanvas.height - margin);
    gridCtx.stroke();

    // 绘制 Y 轴（右边）
    gridCtx.beginPath();
    gridCtx.moveTo(gridCanvas.width - margin, margin);
    gridCtx.lineTo(gridCanvas.width - margin, gridCanvas.height - margin);
    gridCtx.stroke();

    // 绘制中间的垂直线条（Y 轴）
    const midX = margin + ((xMax - xMin) / 2) * xScale; // 计算中间位置
    gridCtx.beginPath();
    gridCtx.moveTo(midX, margin);
    gridCtx.lineTo(midX, gridCanvas.height - margin);
    gridCtx.stroke();

    // 绘制中间的水平线条（X 轴）
    const midY = gridCanvas.height - margin - ((yMax - yMin) / 2) * yScale; // 计算中间位置
    gridCtx.beginPath();
    gridCtx.moveTo(margin, midY);
    gridCtx.lineTo(gridCanvas.width - margin, midY);
    gridCtx.stroke();
}

// 绘制刻度
function drawTicks() {
    const width = gridCanvas.width - 2 * margin;
    const height = gridCanvas.height - 2 * margin;

    // 计算 X 轴和 Y 轴的刻度范围
    const xRange = xMax - xMin;
    const yRange = yMax - yMin;

    // 计算每个刻度的像素大小
    const xScale = width / xRange; // X 轴每个单位对应的像素
    const yScale = height / yRange; // Y 轴每个单位对应的像素

    gridCtx.strokeStyle = lineColor;
    gridCtx.lineWidth = 0.5;

    // 绘制 X 轴刻度（下边）
    for (let x = xMin; x <= xMax; x++) {
        const pixelX = margin + (x - xMin) * xScale;
        gridCtx.beginPath();
        gridCtx.moveTo(pixelX, gridCanvas.height - margin - 5);
        gridCtx.lineTo(pixelX, gridCanvas.height - margin + 0);
        gridCtx.stroke();
    }

    // 绘制 X 轴刻度（上边）
    for (let x = xMin; x <= xMax; x++) {
        const pixelX = margin + (x - xMin) * xScale;
        gridCtx.beginPath();
        gridCtx.moveTo(pixelX, margin - 0);
        gridCtx.lineTo(pixelX, margin + 5);
        gridCtx.stroke();
    }

    // 绘制 Y 轴刻度（左边）
    for (let y = yMin; y <= yMax; y++) {
        const pixelY = gridCanvas.height - margin - (y - yMin) * yScale;
        gridCtx.beginPath();
        gridCtx.moveTo(margin - 0, pixelY);
        gridCtx.lineTo(margin + 5, pixelY);
        gridCtx.stroke();
    }

    // 绘制 Y 轴刻度（右边）
    for (let y = yMin; y <= yMax; y++) {
        const pixelY = gridCanvas.height - margin - (y - yMin) * yScale;
        gridCtx.beginPath();
        gridCtx.moveTo(gridCanvas.width - margin - 5, pixelY);
        gridCtx.lineTo(gridCanvas.width - margin + 0, pixelY);
        gridCtx.stroke();
    }
}

// 绘制四条边
function drawBorders() {
    gridCtx.strokeStyle = lineColor;
    gridCtx.lineWidth = 1;

    // 上边
    gridCtx.beginPath();
    gridCtx.moveTo(margin, margin);
    gridCtx.lineTo(gridCanvas.width - margin, margin);
    gridCtx.stroke();

    // 下边
    gridCtx.beginPath();
    gridCtx.moveTo(margin, gridCanvas.height - margin);
    gridCtx.lineTo(gridCanvas.width - margin, gridCanvas.height - margin);
    gridCtx.stroke();

    // 左边
    gridCtx.beginPath();
    gridCtx.moveTo(margin, margin);
    gridCtx.lineTo(margin, gridCanvas.height - margin);
    gridCtx.stroke();

    // 右边
    gridCtx.beginPath();
    gridCtx.moveTo(gridCanvas.width - margin, margin);
    gridCtx.lineTo(gridCanvas.width - margin, gridCanvas.height - margin);
    gridCtx.stroke();
}

// 绘制波形
function drawWaveforms() {
    waveformCtx.clearRect(0, 0, waveformCanvas.width, waveformCanvas.height); // 清空画布
    const width = waveformCanvas.width - 2 * margin;
    const height = waveformCanvas.height - 2 * margin;

    // 计算 X 轴和 Y 轴的刻度范围
    const xRange = xMax - xMin;
    const yRange = yMax - yMin;

    // 计算每个刻度的像素大小
    const xScale = width / xRange; // X 轴每个单位对应的像素
    const yScale = height / yRange; // Y 轴每个单位对应的像素
    // 遍历每个通道
    ch_list.forEach((ch, index) => {
        if (ch.show) {
            const data = ch_datas[index];
            waveformCtx.strokeStyle = ch.color;
            waveformCtx.lineWidth = ch.weight;
            // 计算每个数据点之间的像素间隔
            const pixelPerPoint = width / (data.length - 1); // 每个数据点之间的像素间隔
            // 绘制波形
            waveformCtx.beginPath();
            for (let i = 0; i < data.length; i++) {
                const x = margin + (i) * pixelPerPoint;
                const y = waveformCanvas.height - margin - (data[i] - yMin) * yScale;
                if (i === 0) {
                    waveformCtx.moveTo(x, y);
                } else {
                    waveformCtx.lineTo(x, y);
                }
            }
            waveformCtx.stroke();
        }
    });
}

// 绘制示波器图表
function drawOscilloscope() {
    gridCtx.clearRect(0, 0, gridCanvas.width, gridCanvas.height); // 清空画布
    drawGrid();
    drawAxes();
    drawTicks();
    drawBorders();
}

// 窗口大小改变时重新绘制
window.addEventListener('resize', () => {
    // 更新 gridCanvas 大小
    // gridCanvas.width = window.innerWidth;
    // gridCanvas.height = window.innerHeight;
    gridCanvas.width = screenElement.clientWidth;
    gridCanvas.height = screenElement.clientHeight;
    waveformCanvas.width = screenElement.clientWidth;
    waveformCanvas.height = screenElement.clientHeight;
    // 重新绘制图表
    drawOscilloscope();
    // 重新绘制波浪
    drawWaveforms();
});

// 监听通道改变
ChannellAPI.linstenChannel(() => {
    loadModel();
});

// 创建按钮
function createButtons() {
    const container = document.getElementById('channelList');
    container.innerHTML = ''; // 清空旧按钮

    for (let i = 0; i < ch_list.length; i++) {
        const ch = ch_list[i];
        const btn = document.createElement('button');
        btn.textContent = `CH${i + 1}`;
        btn.className = 'channel-button';
        btn.style.color = ch.show ? 'black' : ch.color;
        btn.style.backgroundColor = ch.show ? ch.color : 'white';
        btn.addEventListener('click', async () => {
            ch.show = !ch.show;
            updateChannelModel(ch);
            // // 重新绘制图表
            // drawOscilloscope();
        });
        container.appendChild(btn);
    }
}


document.addEventListener('DOMContentLoaded', function () {
    drawOscilloscope();
    loadModel();
});

///更新通道信息
async function updateChannelModel(ch) {
    const result = await ChannellAPI.updateChannel(ch);
    if (result.success == false) {
        alert(`${result.error}`);
    }
}

let ch_list = [];
// 通道数据（示例数据）
const ch_datas = Array.from({ length: 6 }, () => generateRandomData());
async function loadModel() {
    ch_list = await ChannellAPI.getAllChannel;

    // 生成 6 个按钮
    createButtons();
    drawWaveforms();
}

// 生成随机数据（示例）
function generateRandomData() {
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    const num = getRandomInt(-20, 20);
    const data = [];
    for (let i = 0; i <= xMax * 0.3; i++) {
        data.push(Math.sin((i / xMax) * num * Math.PI) * 20); // 正弦波示例
    }
    return data;
}
